<?php
namespace app\admin\controller;
use app\admin\model\ModuleStoreModel;
use app\admin\model\ModulePluginModel;
use think\Model;
use app\admin\model\UserModel;
use think\Db;

use cmf\controller\AdminBaseController;

class ModulePluginController extends AdminBaseController
{
	public function index()
	{
		$param = $this->request->param();
		
		$search = [
			'mid' => isset( $param [ 'mid' ] ) ? $param ['mid'] : 0 ,
		];
		$all = ModuleStoreModel::where( 'version' , 'B' )->order('name')->select();
		
		$list = ModulePluginModel::order('name,version');
		if( $search [ 'mid' ] != 0 ){
			$list = $list -> where( 'mid' , $search [ 'mid' ] );
		}
		$list = $list->select();
	
		$this->assign( 'search' , $search );		
		$this->assign( 'all' , $all );
		$this->assign( 'list' , $list );
		
		return $this->fetch( 'module_manage/plugin/index' );
	}
	
	public function addPage()
	{
		$all = ModuleStoreModel::where( 'version' , 'B' )->order('name')->select();
		$this->assign( 'all' , $all );
		return $this->fetch( 'module_manage/plugin/addPage' );
	}
	
	public function addPluginPost()
	{
		$param = $this->request->param();
		$rule = [
			'mid' => 'require',
			'name' => 'require|alpha',
			'title' => 'require',
		];
		$msg = [
			'mid.require' => '所属模块不能为空',
			'name.require' => '标识不能为空',
			'name.alpha' => '标识只能是英文字母',
			'title.require' => '标题不能为空',
		];
		
		$result = new \think\Validate( $rule , $msg )  ;
		if( !$result->check ( $param ) ){
			return api_json_echo( false , $result->getError() , null , 100 );
		}
		
		$find = ModulePluginModel::where( 'name' , $param[ 'name' ] )->column( 'version' );
		
		$versions =  $this->sortVersion( $find );
		
		if( empty( $versions) ){
			$lastVersion = '1.0';
		}else{
			$max = reset( $versions);
			$lastVersion = $this->progressiveIncreaseVersion( $max );
		}
		$param [ 'version' ] = $lastVersion;
		$param [ 'word' ] = $this->getWordNo( $param [ 'mid' ] , $param[ 'name' ] , $param [ 'title' ] );
		$param [ 'author_id' ] = cmf_get_current_admin_id();
		$param [ 'author' ] = Db::name('user')->where('id',$param['author_id'])->value('user_login');
		
		if( !( new ModulePluginModel() ) -> allowField(true)->isUpdate(false)->save( $param ) ){
			return api_json_echo( false , '添加失败' );
		}
		return api_json_echo( true , '添加成功' );
		
	}
	
	public function editPage( $id )
	{
		$da = ModulePluginModel::get( $id );
		$all = ModuleStoreModel::where( 'version' , 'B' )->order('name')->select();
		$this->assign( 'da' , $da );
		$this->assign( 'all' , $all );
		return $this->fetch( 'module_manage/plugin/editPage' );
	}
	
	public function editPluginPost()
	{
		$param = $this->request->param();
		$rule = [
			'mid' => 'require',
			'name' => 'require|alpha',
			'title' => 'require',
		];
		$msg = [
			'mid.require' => '所属模块不能为空',
			'name.require' => '标识不能为空',
			'name.alpha' => '标识只能是英文字母',
			'title.require' => '标题不能为空',
		];
		
		$result = new \think\Validate( $rule , $msg )  ;
		if( !$result->check ( $param ) ){
			return api_json_echo( false , $result->getError() , null , 100 );
		}
		if( ! (new ModulePluginModel())->allowField(true)->isUpdate(true)->update( $param ) ){
			return api_json_echo( false , '更新失败' );
		}
		return api_json_echo( true , '更新成功' );
	}
	
	
	
	public function updates()
	{
		$param = $this->request->param();
		//dump( $param );exit;
		if( !( new ModulePluginModel() )->allowField(true)->isUpdate( true )->save( $param ) ){
			return api_json_echo( false , '更新失败' , null , 102 );
		}
		return api_json_echo( true , '更新成功' );
	}
	
	
	public function del($id)
	{
		$find = ModulePluginModel::get( $id );
	
		if( !$find ){
			return api_json_echo( false , '数据不存在' );
		}

		//delete word
		$this->deleteWord( $find[ 'word' ] );
		//delete module
		if( !ModulePluginModel::destroy( $id ) ){
			return api_json_echo( false , '删除失败' );
		}		
		return api_json_echo( true , '删除成功' );
		
	}
	
	private function deleteWord( $id ){
		//$count = ModulePluginModel::where('word',$id)->count();
		//if($id && $count == 1 )
		//db( 'word' )->delete( $id );
	}
	
	
	private function getWordNo( $mid , $name , $title )
	{
		$findModule = ModuleStoreModel::get( $mid );
		
		$wordNo = $findModule->word;
		
		//模块下 名为插件的目录 
		$findPluginDir = DB('word')->where( 'content' , 'THISPLUGINDIRFOR'.$wordNo )->value( 'id' );
		
		if( empty( $findPluginDir ) ){
			$word = [
				'name' => '插件',
				'type' => 1,
				'parent_id' => $wordNo,
				'content' => 'THISPLUGINDIRFOR'.$wordNo,
				'create_time' => time(),
				'create_user' => cmf_get_current_admin_id()
			];
			$findPluginDir = Db('word')->insertGetId( $word );
		}
		
		//创建插件目录
		
		 
				
		$word = [
			'name' => $title,
			'type' => 1,
			'parent_id' => $findPluginDir,
			'content' => 'PLUGIN_'.strtoupper( $name ),
			'create_time' => time(),
			'create_user' => cmf_get_current_admin_id()
		];
		
		$where = [
			'PLUGIN_'.strtoupper( $name ),
		];
		$id  = Db('word')->where( 'content' , $word[ 'content' ] )->value( 'id' );
		if( !$id ){
			$id = Db('word')->insertGetId( $word );
		}
		return $id;
	}
	
	
	
	
	//比较两个版本大小 假定 $first < $second  = true    否则为 false 
	
	private function compareVersion( $first , $second )
	{
		$first = explode( '.' , $first );
		$second = explode( '.' , $second );
		
		$len = count( $first );
		if( count( $second ) < count( $first ) ){
			$len = count($second);
		}
		$res = true;
		for( $i=0;$i<$len;$i++){
			if( $first[ $i ] > $second [ $i ] ){
				$res = false;
				break;
			}else if( $first[ $i ] < $second [ $i ] ){
				break;
			}
			
			if( $i == $len-1 && $res == true && count( $first ) == count( $second ) ){
				$res = false;
			}
		}
		
		return $res;
	}
	
	//sort versions 
	private function sortVersion( $versions )
	{
		for( $i=0 ; $i< count( $versions ) ; $i++ ){
			for( $j=0 ; $j < count( $versions )-1-$i;$j++){
				if( $this->compareVersion( $versions [ $j ] , $versions [ $j+1 ] ) ){
					$tmp = $versions [$j];
					$versions [ $j ] = $versions [ $j+1 ];
					$versions [ $j+1 ] = $tmp;
				}
			}
		}
		return $versions;
	}
	
	//版本递增
	private function progressiveIncreaseVersion( $version )
	{
		$arr = explode( '.' , $version );
		if( $arr[1] + 1 > 10 ){
			$arr[1] = 0 ;
			$arr[0] += 1;
		}else{
			$arr[1]+=1;
		}
		return implode( '.' , $arr );
	}
	
	
}